package com.demonzym.framework.net.httpsocket.xml;

import java.io.IOException;
import java.io.InputStream;
import java.net.SocketTimeoutException;

import com.demonzym.framework.log.MyLog;


public class NMMPResponseInputStream extends InputStream {
    InputStream mIn;
    boolean mStartOfLine = true;
    boolean mFinished;
    boolean mFirst=true;
    int count=0;
    int totalcount=0;
    private static final String TAG = "NMMPResponseInputStream";
    public NMMPResponseInputStream(InputStream in) {
        mIn = in;
    }
    private int getPacketSize(byte[] data) {
    	int packetSize = 0;
    	packetSize = (data[0] << 24 & 0xff000000);
    	packetSize += (data[1] << 16 & 0x00ff0000);
    	packetSize += (data[2] << 8 & 0x0000ff00);	
    	packetSize += (data[3] & 0x000000ff);	
    	return packetSize;
    }
    @Override
    public int read() throws IOException {        	
        if (mFinished) {
            return -1;
        }
        if(mFirst){
        	mFirst=false;
        	byte [] charlength=new byte[4];                
        	int i=mIn.read(charlength,0,4);
        	if(i==0){
        		mFinished=true;
            	return -1;
        	}
        		
            totalcount=getPacketSize(charlength);
        }
        if(count++>=totalcount){
        	mFinished=true;
        	return -1;
        }
        int d = 0;

		//
		try{
			d = mIn.read();
		}
		catch (SocketTimeoutException e) {
				e.printStackTrace();
				close();				
				MyLog.e(TAG,"NMMPResponseInputStream read SocketTimeoutException");
				throw new IOException("NMMPResponseInputStream read SocketTimeoutException");
			//}
    	}catch (IOException e) {
            // May fail if the connection is already closed.
    		//Log.e(TAG,"NmmpTransport getPrimitive IOException");
    		MyLog.e(TAG,"NMMPResponseInputStream read IOException");
    		throw new IOException("NMMPResponseInputStream read IOException");
        }
    	catch (Exception e) {
            // May fail if the connection is already closed.
    		MyLog.e(TAG,"NMMPResponseInputStream read Exception");
    		throw new IOException("NMMPResponseInputStream read Exception");
        }
		//
		
        /*if (mStartOfLine && d == '.') {
            d = mIn.read();
            if (d == '\r') {
                mFinished = true;
                mIn.read();
                return -1;
            }
        }*/

       // mStartOfLine = (d == '\n');

        return d;
    }
}
